<template>
    <div class="py-4 border-b">
        <div class="text-2xl">{{work.question}}</div>
        <div v-if="work.description" v-html="work.description"></div>
        <div v-if="isSubmitted && work.mark!==null">
            分数{{work.mark}}分
        </div>
        <div class="selections">
            <template v-if="work.type===1" v-for="(selection,index) in work.selections">
                <div v-if="isSubmitted">
                    <input type="radio" disabled :checked="work.user_result===index?'checked':''"> {{selection.value}}
                </div>
                <div v-else>
                    <input type="radio" v-model="result" :value="index"> {{selection.value}}
                </div>
            </template>
            <template v-if="work.type===2" v-for="(selection,index) in work.selections">
                <div v-if="isSubmitted">
                    <input type="checkbox" disabled :checked="work.user_result.indexOf(index)!==-1?'checked':''">
                    {{selection.value}}
                </div>
                <div v-else>
                    <input type="checkbox" v-model="result" :value="index"> {{selection.value}}
                </div>

            </template>
            <template v-if="work.type===3">
                <div v-if="!isSubmitted">
                    <input type="file" ref="fileInt" @change="changeHandle">
                </div>
                <div v-else><a :href="'/storage/attachment/work/'+work.user_result" download>下载文件</a></div>
            </template>
        </div>

    </div>
</template>

<script>
    export default {
        props: {work: {type: Object, required: true}},
        data() {
            return {result: null}
        }, watch: {
            result() {
                this.check();
            }
        }, computed: {
            isSubmitted() {
                // console.log(this.work.user_result.length)
                return !!this.work.user_result;
            }
        },
        methods: {
            check() {
                this.$emit('complete', {id: this.work.id, result: this.result});
            }, changeHandle() {
                const file = this.$refs.fileInt.files[0];
                console.log(file);
                const data = new FormData();
                data.append('attachment', file);
                axios.post('works/upload', data, {
                    headers: {
                        'Content-Type': 'multipart/form-data',
                    },
                }).then(res => {
                    console.log(res);
                    this.result = res.data;
                }).catch(err => {
                    console.log(err);
                });
            }
        }, created() {
            if (this.work.type === 2) {
                this.result = [];
            }
            console.log(this.work)
        }
    }
</script>

<style scoped>

</style>